﻿@using System.ComponentModel.DataAnnotations
@inject IUserBasketService basketService
@inject IUserService userService
@inject ClientStatusService statusService
@inject IConfigService configService
@inject ILogger<BasketDialog> logger

<MudDialog>
    <TitleContent>
        <MudText Typo="Typo.h6">@(Mode == "Edit" ? $"Edit Basket '{Basket.Name}'" : "Create New Basket") </MudText>
    </TitleContent>
    <DialogContent>
        <EditForm Model="@model" OnValidSubmit="OnValidSubmit">
            <DataAnnotationsValidator/>
            <MudTextField @bind-Value="@model.BasketName" For="@(() => model.BasketName)" Label="Basket Name" ReadOnly="false" Variant="Variant.Filled" UserAttributes="@MudNoAutofill.noAutoFillAttr"/>
            @if( configService.GetBool(ConfigSettings.EnablePoliciesAndRoles) )
            {
                <MudCheckBox @bind-Value="@model.IsPublic" Label="Share this basket with other users"/>
            }
            @if( !string.IsNullOrEmpty(errorMsg) )
            {
                <p>@errorMsg</p>
            }
        </EditForm>
    </DialogContent>
    <DialogActions>
        @if( Mode == "Edit" )
        {
            <MudItem xs="12" md="12">
                <MudPaper Elevation="0" Class="d-flex py-2 px-1">
                    <MudButton Class="pa-2 ml-2 mr-auto" Color="Color.Warning" OnClick="DeleteBasket">Delete Basket</MudButton>
                    <MudButton Class="pa-2 mx-2" OnClick="Cancel">Cancel</MudButton>
                    <MudButton Class="pa-2 mx-2" Color="Color.Primary" OnClick="Save">Save</MudButton>
                </MudPaper>
            </MudItem>
        }
        else
        {
            <MudButton OnClick="Cancel">Cancel</MudButton>
            <MudButton Color="Color.Primary" OnClick="Save">Add Basket</MudButton>
        }
    </DialogActions>
</MudDialog>

@code {

    [CascadingParameter] MudDialogInstance MudDialog { get; set; }

    [Parameter] public Basket Basket { get; set; } = new();

    [Parameter] public string Mode { get; set; }

    public class BasketForm
    {
        [Required] public string BasketName { get; set; }

        public bool IsPublic { get; set; }
    }

    private readonly BasketForm model = new();

    private async Task OnValidSubmit(EditContext context)
    {
        await Save();
    }

    async Task DeleteBasket()
    {
        await basketService.Delete(Basket.BasketId);

        if( model.IsPublic )
            statusService.UpdateGlobalStatus($"Basket '{model.BasketName}' was deleted.");
        else
            statusService.UpdateStatus($"Basket '{model.BasketName}' was deleted.");

        // Force it to reload a new basket
        await basketService.SwitchToDefaultBasket(userService.UserId);

        MudDialog.Close(DialogResult.Ok(true));
    }

    async Task Save()
    {
        try
        {
            int? userId = null;

            if( !model.IsPublic )
                userId = userService.UserId;

            if( Mode == "Add" )
            {
                var newBasket = await basketService.Create(model.BasketName, userId);

                // Force it to reload
                await basketService.SwitchToBasket(newBasket.BasketId);

                if( model.IsPublic )
                    statusService.UpdateGlobalStatus($"Basket '{model.BasketName}' created.");
                else
                    statusService.UpdateStatus($"Basket '{model.BasketName}' created.");
            }
            else if( Mode == "Edit" )
            {
                Basket.Name = model.BasketName;
                Basket.UserId = userId;
                await basketService.Save(Basket);

                if( model.IsPublic )
                    statusService.UpdateGlobalStatus($"Basket '{model.BasketName}' saved.");
                else
                    statusService.UpdateStatus($"Basket '{model.BasketName}' saved.");
            }

            MudDialog.Close(DialogResult.Ok(true));

            StateHasChanged();
        }
        catch( Exception ex )
        {
            logger.LogError($"Unexpected error saving basket details: {ex}");
            DisplayError($"Unexpected error saving basket {ex.Message}");
        }
    }

    private string errorMsg;

    private void DisplayError(string errorText)
    {
        errorMsg = errorText;
        StateHasChanged();
    }

    void Cancel()
    {
        MudDialog.Cancel();
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();

        model.BasketName = Basket.Name;
        if( configService.GetBool(ConfigSettings.EnablePoliciesAndRoles) )
        {
            model.IsPublic = Basket.UserId == null;
        }
        else
        {
            // Always shared/public if roles are disabled
            model.IsPublic = true;
        }
    }

}